package com.example.maruko_course_backend.services.impl;

import com.example.maruko_course_backend.dto.EditedGrammar;
import com.example.maruko_course_backend.dto.GrammarContentDto;
import com.example.maruko_course_backend.entity.Grammar;
import com.example.maruko_course_backend.entity.Sentence;
import com.example.maruko_course_backend.repositories.SentenceRepository;
import com.example.maruko_course_backend.services.EditSentenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class EditSentenceServiceImpl implements EditSentenceService {
  
  @Autowired
  private SentenceRepository sentenceRepository;
  
  @Override
  public Sentence saveOrModifyGrammar(String videoNum, String seq, EditedGrammar editedGrammar) {
    Sentence sentence = sentenceRepository.findAllByUpVideoNumAndSentenceSeq(Integer.parseInt(videoNum), Integer.parseInt(seq));
    updateSentence(sentence, editedGrammar);
    return sentenceRepository.save(sentence);
  }
  
  private void updateSentence(Sentence sentence, EditedGrammar editedGrammar) {
    if (CollectionUtils.isEmpty(editedGrammar.getContentList())) {
      return;
    }
    if (CollectionUtils.isEmpty(sentence.getGrammars())) {
      sentence.setGrammars(new ArrayList<>());
    }
    Grammar grammar = converToGrammar(editedGrammar.getCategory(), editedGrammar.getContentList().get(0));
    sentence.getGrammars().add(grammar);
  }
  
  private static Grammar converToGrammar(String category, GrammarContentDto grammarContentDto) {
    return Grammar.builder()
      .category(category)
      .seq(Integer.valueOf(grammarContentDto.getSeq()))
      .content(grammarContentDto.getContent())
      .build();
  }
}
